const urlPrefix = "http://localhost:8080/"
const selectedCategories = new Set();
const newAddCategories = new Set();
const newDelCategories = new Set();

const allCategories = new Map();
const task = {
    taskId: 0,
    taskName: "",
    categoryList: [],
    urlList: [],
    taskDefine: "",
    taskDescription: "",
}

// 添加类别标签
function addCategoryTag(value, text) {
    const tag = $(`
                <div class="category-tag" data-value="${value}">
                    ${text}
                    <span class="remove">×</span>
                </div>
            `);

    tag.find('.remove').on('click', function () {
        $(this).parent().remove();
        selectedCategories.delete(value);
    });

    $('.selected-tags').append(tag);
}

// 创建类别项
function createCategoryItem(text, value) {
    const item = $(`
            <div class="category-item" data-value="${value}">
                <span class="category-text">${text}</span>
                <button class="delete-btn">删除</button>
            </div>
        `);

    item.find('.delete-btn').on('click', function () {
        const $item = $(this).closest('.category-item');
        // 检查该类别是否已被选中
        const value = $item.data('value').toString();
        if (selectedCategories.has(value)) {
            showAlert('该类别已被选中，无法删除');
            return;
        }
        $item.remove();
        newDelCategories.add(value);
    });

    return item;
}

$(document).ready(function () {
    // 查询所有类别
    $.get(urlPrefix + "category/queryAll", function (response) {
        if (response.code !== "200") {
            showAlert(response.msg)
            return
        }
        const data = response.data
        const selector = $("#category")
        for (let item of data) {
            allCategories.set(item.categoryId.toString(), item.categoryName)
            selector.append(`<option value="${item.categoryId}">${item.categoryName}</option>`)
        }
        // 重新渲染select组件
        selector.show()
    }).fail(function (xhr, status, error) {
        layer.msg("获取类别失败：" + status + " " + error);
    });

    // 修改类别管理按钮的点击事件
    $('#newCategory').on('click', function () {
        newAddCategories.clear()
        newDelCategories.clear()
        // 创建类别管理模态框
        const modalHtml = `
            <div class="modal-overlay">
                <div class="modal-content category-manager">
                    <h3>类别管理</h3>
                    <div class="category-list"></div>
                    <div class="add-category">
                        <input type="text" id="newCategoryInput" placeholder="输入新类别名称">
                        <button class="add-btn">添加</button>
                    </div>
                    <div class="modal-buttons">
                        <button class="modal-confirm">确定</button>
                        <button class="modal-cancel">取消</button>
                    </div>
                </div>
            </div>
        `;
        // 移除可能存在的旧模态框
        $('.modal-overlay').remove();

        // 添加新的模态框
        $('body').append(modalHtml);

        // 加载现有类别
        const $categoryList = $('.category-list');
        allCategories.forEach((v, k, m) => {
            $categoryList.append(createCategoryItem(v, k))

        })
        $categoryList.show()

        // 添加新类别的处理
        $('.add-btn').on('click', function () {
            const value = $('#newCategoryInput').val().trim();
            if (value === '') {
                showAlert('类别名称不能为空');
                return;
            }

            // 检查是否已存在相同类别 allCategories+newAddCategories-newDelCategories
            let exists = false;
            if (newAddCategories.has(value)) {
                exists = true;
            } else {
                for (const [k, v] of allCategories) {
                    if (v === value) {
                        if (newDelCategories.has(k)) {
                            break
                        }
                        exists = true;
                        break;
                    }
                }
            }


            if (exists) {
                showAlert('该类别已存在');
                return;
            }

            // 添加新类别到列表
            newAddCategories.add(value)
            $categoryList.append(createCategoryItem(value, ""));
            $('#newCategoryInput').val('');
        });

        // 确认按钮处理
        $('.modal-confirm').on('click', function () {
            // 去除不必要的请求
            if (newAddCategories.size === 0 && newDelCategories.size === 0) {
                $('.modal-overlay').remove();
                return
            }
            // 将新增/删除的类别更新到数据库
            $.ajax({
                url: urlPrefix + "category/update",
                type: "PUT",
                contentType: 'application/json',
                data: JSON.stringify({
                    newAddCategoryList: Array.from(newAddCategories),
                    newDelCategoryList: Array.from(newDelCategories).map(Number)
                }),
                success: function (response) {
                    // 出现业务错误
                    if (response.code !== "200") {
                        showAlert(response.msg)
                        $('.modal-overlay').remove();
                        return
                    }

                    const categoryIdList = response.data
                    const $selector = $('#category');
                    const arr1 = Array.from(newAddCategories)
                    const arr2 = Array.from(newDelCategories)
                    // 更新categoryMap以及select
                    for (let i = 0; i < arr1.length; i++) {
                        allCategories.set(categoryIdList[i].toString(), arr1[i])
                        $selector.append(`<option value="${categoryIdList[i]}">${arr1[i]}</option>`)
                        console.log(arr1[i])
                    }
                    for (let i = 0; i < arr2.length; i++) {
                        allCategories.delete(arr2[i])
                        $selector.find(`option[value="${arr2[i]}"]`).remove()
                        console.log(arr2[i])
                    }
                    $selector.show()
                    $('.modal-overlay').remove();
                },
                error: function (xhr, status, error) {
                    showAlert("类别更新失败：" + status + " " + error);
                    $('.modal-overlay').remove();
                }
            })
        });

        $(".modal-cancel").on("click", function () {
            $('.modal-overlay').remove();
        })
    });

    // 监听select变化
    $('#category').on('change', function () {
        const selectedValue = $(this).val();
        const selectedText = $(this).find('option:selected').text();
        if (selectedValue && selectedValue !== '') {
            // 检查是否已达到最大选择数量
            if (selectedCategories.size >= 3) {
                showAlert('最多只能选择3个类别');
                $(this).val(''); // 重置select
                return;
            }

            // 检查是否已经选择过
            if (selectedCategories.has(selectedValue)) {
                showAlert('该类别已经选择过');
                $(this).val(''); // 重置select
                return;
            }

            // 添加新标签
            addCategoryTag(selectedValue, selectedText);
            selectedCategories.add(selectedValue);
        }

        // 重置select到默认选项
        $(this).val('');
    });

    // 点击新建爬虫菜单项
    $('#create-task').on('click', function () {
        const taskName = $('#task-name').val().trim();
        const urlListStr = $('#url').val().trim()
        const urlList = urlListStr === "" ? [] : urlListStr.split("\n")
        if (!taskName) {
            showAlert('任务名不能为空');
            return;
        }
        if (urlList.length === 0) {
            showAlert('网址不能为空');
            return;
        }
        task.taskDescription = $('#description').val().trim()
        $(".selected-tags .category-tag").each(function () {
            task.categoryList.push($(this).data("value"))
        })
        task.taskName = taskName
        task.urlList = urlList

        $.post({
            url: urlPrefix + "task/create",
            contentType: 'application/json', // 设置请求头为 JSON
            data: JSON.stringify({
                taskName: task.taskName,
                categoryList: task.categoryList,
                urlList: task.urlList,
                taskDescription: task.taskDescription,
            }), // 将参数转换为 JSON 字符串
            success: function (response) {
                // 业务错误
                if (response.code !== "200") {
                    showAlert("任务创建失败：" + response.msg)
                    return
                }
                task.taskId = response.data
                // 页面切换至 crawler_edit
                window.pageEvent.switchPage(1, {
                    task: task,
                    allCategories: allCategories
                })
            },
            error: function (xhr, status, error) {
                showAlert(`任务创建失败，status:${status}, error:${error}`)
            }
        });
    })
    // 点击爬虫管理菜单项
    $('#crawler-manage').on('click', function () {
        // 页面切换至 crawler_edit
        window.pageEvent.switchPage(2, allCategories)
    })
})